package org.csu.onlineedubackend.service.impl;

import org.csu.onlineedubackend.entity.FriendRelationship;
import org.csu.onlineedubackend.entity.FriendRequest;
import org.csu.onlineedubackend.entity.Notification;
import org.csu.onlineedubackend.entity.User;
import org.csu.onlineedubackend.mapper.FriendRelationshipMapper;
import org.csu.onlineedubackend.mapper.FriendRequestMapper;
import org.csu.onlineedubackend.mapper.UserMapper;
import org.csu.onlineedubackend.service.FriendService;
import org.csu.onlineedubackend.service.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class FriendServiceImpl implements FriendService {

    @Autowired
    private FriendRequestMapper friendRequestMapper;
    
    @Autowired
    private FriendRelationshipMapper friendRelationshipMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private NotificationService notificationService;
    
    @Override
    public FriendRequest sendFriendRequest(Integer senderId, Integer receiverId) {
        // 检查是否已经是好友
        if (friendRelationshipMapper.areFriends(senderId, receiverId)) {
            throw new RuntimeException("你们已经是好友了");
        }
        
        // 检查是否已经发送过申请
        FriendRequest existingRequest = friendRequestMapper.findBySenderAndReceiver(senderId, receiverId);
        if (existingRequest != null && "PENDING".equals(existingRequest.getStatus())) {
            throw new RuntimeException("已经发送过好友申请，请等待对方回应");
        }
        
        // 创建新的好友申请
        FriendRequest friendRequest = new FriendRequest();
        friendRequest.setSenderId(senderId);
        friendRequest.setReceiverId(receiverId);
        friendRequest.setStatus("PENDING");
        
        friendRequestMapper.insert(friendRequest);
        
        // 获取发送者和接收者信息
        User sender = userMapper.findById(senderId);
        User receiver = userMapper.findById(receiverId);
        
        friendRequest.setSender(sender);
        friendRequest.setReceiver(receiver);
        
        // 创建通知给接收者
        Notification notificationForReceiver = new Notification();
        notificationForReceiver.setUserId(receiverId);
        notificationForReceiver.setType("FRIEND_REQUEST");
        notificationForReceiver.setTargetName(sender.getName());
        notificationForReceiver.setTargetId(senderId);
        notificationForReceiver.setTitle("好友申请通知");
        notificationForReceiver.setContent(sender.getName() + " 想添加您为好友");
        notificationForReceiver.setIsRead(false);
        notificationForReceiver.setCreatedAt(new Date());
        
        notificationService.addNotification(notificationForReceiver);
        
        // 创建通知给发送者
        Notification notificationForSender = new Notification();
        notificationForSender.setUserId(senderId);
        notificationForSender.setType("FRIEND_REQUEST_SENT");
        notificationForSender.setTargetName(receiver.getName());
        notificationForSender.setTargetId(receiverId);
        notificationForSender.setTitle("好友申请已发送");
        notificationForSender.setContent("您向 " + receiver.getName() + " 发送了好友请求");
        notificationForSender.setIsRead(false);
        notificationForSender.setCreatedAt(new Date());
        
        notificationService.addNotification(notificationForSender);
        
        return friendRequest;
    }
    
    @Override
    @Transactional
    public FriendRelationship acceptFriendRequest(Long requestId, Integer userId) {
        FriendRequest friendRequest = friendRequestMapper.findById(requestId);
        if (friendRequest == null) {
            throw new RuntimeException("好友申请不存在");
        }
        
        if (!friendRequest.getReceiverId().equals(userId)) {
            throw new RuntimeException("无权操作此好友申请");
        }
        
        if (!"PENDING".equals(friendRequest.getStatus())) {
            throw new RuntimeException("该好友申请已处理");
        }
        
        // 更新申请状态
        friendRequestMapper.updateStatus(requestId, "ACCEPTED");
        
        // 创建双向好友关系
        FriendRelationship relationship1 = new FriendRelationship();
        relationship1.setUserId(friendRequest.getReceiverId());
        relationship1.setFriendId(friendRequest.getSenderId());
        friendRelationshipMapper.insert(relationship1);
        
        FriendRelationship relationship2 = new FriendRelationship();
        relationship2.setUserId(friendRequest.getSenderId());
        relationship2.setFriendId(friendRequest.getReceiverId());
        friendRelationshipMapper.insert(relationship2);
        
        // 获取好友信息
        User friend = userMapper.findById(friendRequest.getSenderId());
        relationship1.setFriend(friend);
        
        // 获取用户信息
        User sender = userMapper.findById(friendRequest.getSenderId());
        User receiver = userMapper.findById(friendRequest.getReceiverId());
        
        if (sender != null) {
            // 删除接收者的好友申请通知，或更新其状态
            notificationService.deleteNotificationsByType(userId, "FRIEND_REQUEST", sender.getName());
        }
        
        if (receiver != null && sender != null) {
            // 只更新发送者的待处理通知状态，不创建新通知
            notificationService.updateNotificationTypeByUserAndTarget(friendRequest.getSenderId(), "FRIEND_REQUEST_SENT", receiver.getName(), "FRIEND_REQUEST_ACCEPTED");
        }
        
        return relationship1;
    }
    
    @Override
    public FriendRequest rejectFriendRequest(Long requestId, Integer userId) {
        FriendRequest friendRequest = friendRequestMapper.findById(requestId);
        if (friendRequest == null) {
            throw new RuntimeException("好友申请不存在");
        }
        
        if (!friendRequest.getReceiverId().equals(userId)) {
            throw new RuntimeException("无权操作此好友申请");
        }
        
        if (!"PENDING".equals(friendRequest.getStatus())) {
            throw new RuntimeException("该好友申请已处理");
        }
        
        // 更新申请状态
        friendRequestMapper.updateStatus(requestId, "REJECTED");
        
        // 获取用户信息
        User sender = userMapper.findById(friendRequest.getSenderId());
        User receiver = userMapper.findById(friendRequest.getReceiverId());
        
        if (sender != null) {
            // 删除接收者的好友申请通知，或更新其状态
            notificationService.deleteNotificationsByType(userId, "FRIEND_REQUEST", sender.getName());
        }
        
        if (receiver != null && sender != null) {
            // 只更新发送者的待处理通知状态，不创建新通知
            notificationService.updateNotificationTypeByUserAndTarget(friendRequest.getSenderId(), "FRIEND_REQUEST_SENT", receiver.getName(), "FRIEND_REQUEST_REJECTED");
        }
        
        return friendRequest;
    }
    
    @Override
    public List<FriendRequest> getPendingFriendRequests(Integer userId) {
        List<FriendRequest> requests = friendRequestMapper.findPendingByReceiverId(userId);
        
        // 填充发送者信息
        for (FriendRequest request : requests) {
            User sender = userMapper.findById(request.getSenderId());
            request.setSender(sender);
        }
        
        return requests;
    }
    
    @Override
    public List<FriendRequest> getSentFriendRequests(Integer userId) {
        List<FriendRequest> requests = friendRequestMapper.findBySenderId(userId);
        
        // 填充接收者信息
        for (FriendRequest request : requests) {
            User receiver = userMapper.findById(request.getReceiverId());
            request.setReceiver(receiver);
        }
        
        return requests;
    }
    
    @Override
    public List<User> getFriendList(Integer userId) {
        return friendRelationshipMapper.findFriendsByUserId(userId);
    }
    
    @Override
    @Transactional
    public boolean deleteFriend(Integer userId, Integer friendId) {
        // 获取用户信息，用于通知
        User user = userMapper.findById(userId);
        User friend = userMapper.findById(friendId);
        String userName = user != null ? user.getName() : "未知用户";
        String friendName = friend != null ? friend.getName() : "未知用户";
        
        // 删除双向好友关系
        int count1 = friendRelationshipMapper.deleteByUserAndFriend(userId, friendId);
        int count2 = friendRelationshipMapper.deleteByUserAndFriend(friendId, userId);
        
        if (count1 > 0 && count2 > 0) {
            // 创建通知给被删除的好友
            Notification notificationForFriend = new Notification();
            notificationForFriend.setUserId(friendId);
            notificationForFriend.setType("FRIEND_DELETE");
            notificationForFriend.setTargetName(userName);
            notificationForFriend.setTitle("好友删除通知");
            notificationForFriend.setContent(userName + " 已将您从好友列表中移除");
            notificationForFriend.setIsRead(false);
            notificationForFriend.setCreatedAt(new Date());
            
            notificationService.addNotification(notificationForFriend);
            
            // 创建通知给删除者
            Notification notificationForUser = new Notification();
            notificationForUser.setUserId(userId);
            notificationForUser.setType("FRIEND_DELETE_BY_ME");
            notificationForUser.setTargetName(friendName);
            notificationForUser.setTitle("好友删除通知");
            notificationForUser.setContent("您已将 " + friendName + " 从好友列表中移除");
            notificationForUser.setIsRead(false);
            notificationForUser.setCreatedAt(new Date());
            
            notificationService.addNotification(notificationForUser);
        }
        
        return count1 > 0 && count2 > 0;
    }
    
    @Override
    public boolean areFriends(Integer userId1, Integer userId2) {
        return friendRelationshipMapper.areFriends(userId1, userId2);
    }
    
    @Override
    public List<User> searchUsers(String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return new ArrayList<>();
        }
        
        // 在用户名和姓名中搜索
        return userMapper.searchByUsernameOrName(keyword);
    }
    
    @Override
    public List<FriendRequest> getAllFriendRequests(Integer userId) {
        List<FriendRequest> receivedRequests = friendRequestMapper.findAllByReceiverId(userId);
        List<FriendRequest> sentRequests = friendRequestMapper.findBySenderId(userId);

        Map<Long, FriendRequest> requestMap = new java.util.HashMap<>();
        
        for (FriendRequest request : receivedRequests) {
            User sender = userMapper.findById(request.getSenderId());
            request.setSender(sender);
            requestMap.put(request.getId(), request);
        }

        for (FriendRequest request : sentRequests) {
            if (!requestMap.containsKey(request.getId())) {
                 User receiver = userMapper.findById(request.getReceiverId());
                 request.setReceiver(receiver);
                 requestMap.put(request.getId(), request);
            }
        }
        
        List<FriendRequest> allRequests = new java.util.ArrayList<>(requestMap.values());
        allRequests.sort((r1, r2) -> r2.getCreatedAt().compareTo(r1.getCreatedAt()));

        return allRequests;
    }
    
    @Override
    @Transactional
    public FriendRelationship acceptFriendRequestFromNotification(Integer senderId, Integer receiverId, Long notificationId) {
        // 检查是否已经是好友
        if (friendRelationshipMapper.areFriends(senderId, receiverId)) {
            throw new RuntimeException("你们已经是好友了");
        }
        
        // 创建双向好友关系
        FriendRelationship relationship1 = new FriendRelationship();
        relationship1.setUserId(receiverId);
        relationship1.setFriendId(senderId);
        friendRelationshipMapper.insert(relationship1);
        
        FriendRelationship relationship2 = new FriendRelationship();
        relationship2.setUserId(senderId);
        relationship2.setFriendId(receiverId);
        friendRelationshipMapper.insert(relationship2);
        
        // 获取好友信息
        User friend = userMapper.findById(senderId);
        relationship1.setFriend(friend);
        
        // 更新接收者的通知状态为已接受
        notificationService.updateNotificationType(notificationId, "FRIEND_REQUEST_ACCEPTED_BY_ME");
        
        // 获取用户信息
        User sender = userMapper.findById(senderId);
        User receiver = userMapper.findById(receiverId);
        
        if (receiver != null && sender != null) {
            // 只更新发送者的待处理通知状态，不创建新通知
            notificationService.updateNotificationTypeByUserAndTarget(senderId, "FRIEND_REQUEST_SENT", receiver.getName(), "FRIEND_REQUEST_ACCEPTED");
        }
        
        return relationship1;
    }
    
    @Override
    @Transactional
    public boolean rejectFriendRequestFromNotification(Integer senderId, Integer receiverId, Long notificationId) {
        // 更新接收者的通知状态为已拒绝
        notificationService.updateNotificationType(notificationId, "FRIEND_REQUEST_REJECTED_BY_ME");
        
        // 获取用户信息
        User sender = userMapper.findById(senderId);
        User receiver = userMapper.findById(receiverId);
        
        if (receiver != null && sender != null) {
            // 只更新发送者的待处理通知状态，不创建新通知
            notificationService.updateNotificationTypeByUserAndTarget(senderId, "FRIEND_REQUEST_SENT", receiver.getName(), "FRIEND_REQUEST_REJECTED");
        }
        
        return true;
    }
} 